<template>
  <div>
    <h1>监听本地数据缓存</h1>
    <hr>
    <h2>品牌管理案例</h2>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>资产名称</th>
          <th>价格</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in list"
            :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>{{item.time}}</td>
          <td><a href="javascript:;"
               @click="delFn(item.id)">删除</a></td>
        </tr>
        <tr>
          <td>统计</td>
          <td>总价钱为：{{isAll}}</td>
          <td>平均价钱为：{{avage}}</td>
        </tr>
      </tbody>
    </table>
    <input type="text"
           v-model="Sname">
    <input type="text"
           v-model.number="Sprice">
    <button @click="addFn">添加一条数据</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // list: [
      //   {
      //     id: 1,
      //     name: '衣服',
      //     price: 199,
      //     time: new Date()
      //   },
      //   {
      //     id: 2,
      //     name: '鞋子',
      //     price: 129,
      //     time: new Date()
      //   },
      //   {
      //     id: 3,
      //     name: '袜子',
      //     price: 159,
      //     time: new Date()
      //   }
      // ],
      Sname: '',
      Sprice: 0,
      list: JSON.parse(localStorage.getItem('Plist')) || []
    }
  },
  methods: {
    addFn () {
      let id = this.list.length + 1;
      if (this.Sname.length == '' || this.Sprice === 0) {
        alert('请输入完整信息')
        return
      }
      this.list.push({
        id: id,
        name: this.Sname,
        price: this.Sprice,
        time: new Date()
      })
    },
    delFn (id) {
      let index = this.list.findIndex(item => item.id === id)
      this.list.splice(index, 1)
    }
  },
  computed: {
    isAll () {
      return this.list.reduce((item, obj) => item += obj.price, 0)
    },
    avage () {
      return (this.isAll / this.list.length).toFixed(2)
    }
  },
  watch: {
    list: {
      handler () {
        localStorage.setItem('Plist', JSON.stringify(this.list))
      },
      deep: true,
    }
  }
}
</script>

<style scoped>
td {
  border: 1px solid #ccc;
}
table {
  width: 500px;
  text-align: center;
  border: 1px solid #ccc;
}
</style>